package com.thinkcms.security.license;

import cn.hutool.core.io.FileUtil;
import com.thinkcms.core.utils.Checker;
import com.thinkcms.core.utils.SecurityConstants;

import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class LicenseInterceptor implements Interceptor {

    @Override
    public Map<String,Object> before(Object proxy, Object target, Method method, Object[] args) {
        Map<String,Object> params=new LinkedHashMap<>(16);
        String path=args[0].toString()+ SecurityConstants.LICENSE_NAME;
        boolean exist=FileUtil.exist(path);
        if(exist){
            List<String> properties= FileUtil.readUtf8Lines(path);
            if(Checker.BeNotEmpty(properties)){
                properties.forEach(propertie->{
                    if(Checker.BeNotBlank(propertie)){
                        String[] kv=propertie.split(SecurityConstants.LICENSE_NAME_SPLIT);
                        params.put(kv[0],kv[1]);
                    }
                });
            }
        }
        return params;
    }

    @Override
    public void around(Object proxy, Object target, Method method, Object[] args) {

    }

    @Override
    public void after(Object proxy, Object target, Method method, Object[] args, Map<String,Object> objectMap) {
        if(!objectMap.isEmpty()){
            if(target instanceof VerifyLicenseImpl){
                VerifyLicenseImpl verifyLicense=(VerifyLicenseImpl)target;
                verifyLicense.baseRedisService.set(SecurityConstants.LICENSE_NAME,objectMap, TimeUnit.DAYS.toSeconds(10));
            }
        }
    }
}
